<template>
  <div>
    <div class="node" v-has="{action: 'coupon:list', effect: 'move'}">
    <div class="search_box topSelect">
      
      <div class="searchBox1" style="margin-left: 20px">
        <el-button size="small" plain type="primary" icon="el-icon-search" @click="getQueryData">查询</el-button>     
      </div>
    </div>
    <Panel title="邀请活动" :intro="intro">
      <div slot='ext' class="examine">
        <el-button v-has="{action: 'coupon:add', effect: 'move'}" class="button-offt" type="success" icon="el-icon-plus" @click="()=>editStore()">新增</el-button>
    </div>
    <TableEncapsulation
      slot="body"
      :tableConfig="tableConfig"
      :tableData="tableData"
      >
        <template slot="expand" slot-scope="operation">
              <div class="user-table-box">
                <!-- <div>优惠券</div> -->
                 <div class="user-table" style="width: 60%">
                  <div class="user-tr user-border user-head">
                    <div class="user-td user-th">ID</div>
                    <div class="user-td user-th">优惠券</div>
                    <div class="user-td user-th">类型</div>
                    <div class="user-td user-th">使用时段</div>
                    <div class="user-td user-th">状态</div>
                  </div>
                  <div :class="operation.data.activityCoupons.length==index+1? 'user-tr':'user-tr user-border'" v-for="(item,index) in operation.data.activityCoupons" :key="item.id">
                    <div class="user-td ">{{item.id}}</div>
                    <div class="user-td ">满{{item.thresholdAmount}}减{{item.amount}}</div>
                    <div class="user-td ">{{item.type==1? '会员抵扣':item.type==2? '服务费满减':'总费用满减'}}</div>
                    <div class="user-td ">{{item.startTimeOfDay}}~{{item.endTimeOfDay}}</div>
                    <div class="user-td">{{item.state==1? "未审核":'已审核'}}</div>
                  </div>
                 </div>
              </div>
        </template>
        <template slot="operation" slot-scope="operation">
         
          <el-button size="mini" type="primary" 
            v-has="{action: 'scanCodeActivity:update', effect: 'move'}"
            v-if="operation.row.state==1"
            @click="()=>updateState(operation.row.id, 2)"
          >一键上线</el-button>
          <el-button size="mini" type="danger" icon="el-icon-close"
            v-has="{action: 'scanCodeActivity:update', effect: 'move'}"
            v-if="operation.row.state==2"
            @click="()=>updateState(operation.row.id, 1)"
          >一键下线</el-button>
        </template>
        <TablePager
          slot="pager"
          v-if="pager.use"
          :size="pager.size"
          :pageChange="pageChange"
          :show-total="pager.showTotal"
          :total="pager.total"
          :current="pager.current"
          layout="sizes, prev, pager, next"
        >
          <span class="demonstration">GO></span>
        </TablePager>
    </TableEncapsulation>
    </Panel>
    <!-- 添加编辑 start-->
    <ModalPanel 
      :visible='visible'
      title="添加/编辑"
      :showFooter='showUpdate'
      :onCancel="onCancel"
      class="bannerDialog"
      :onOk="onSubmit">
      <div>
        <ModifyForm
          :hiddenBtn='true'
          :editColumn='editColumn'
          :updateData="updateData"
          labelWidth='100px'
          ref="configModal"
          class="ModifyForm"
          :temporaryData='modalData'>
          <div slot="timeTamp">
            <el-date-picker
            v-model="appointmentTime"
            format="yyyy-MM-dd HH:mm:ss"
            type="datetime"
            placeholder="选择日期">
          </el-date-picker>
          </div>
        <div slot="CouponList">
          <div>
            <span v-for="(item,index) in couponItems" :key="index" @click="deleteCouponItems(index)" class="coupon-item el-icon-circle-close">{{item.name}}(id:{{item.id}})</span>
          </div>
            <TableEncapsulation
              slot="body"
              :tableConfig="tableConfigCoupon"
              :tableData="tableDataCoupon"
              >
              <template slot="operation" slot-scope="operation">
                <el-button size="mini" type="primary" 
                  @click="()=>addCouponItems(operation.row)"
                >添加</el-button>
              </template>
                <TablePager
                  slot="pager"
                  v-if="pager1.use"
                  :size="pager1.size"
                  :pageChange="pageChange1"
                  :show-total="pager1.showTotal"
                  :total="pager1.total"
                  :current="pager1.current"
                  layout="sizes, prev, pager, next"
                >
                  <span class="demonstration">GO></span>
                </TablePager>
            </TableEncapsulation>
        </div>
        <div slot="siteBoxSlot">
          <el-checkbox-group v-model="checkList">
            <el-checkbox  v-for="(item,index) in typesList" :key="index" :label="item.id+''">{{item.name}}</el-checkbox>
          </el-checkbox-group>
        </div>
        </ModifyForm>
      </div>
    </ModalPanel>
    <!-- 添加编辑end -->
    </div>
    <div style="display: none;width:100%;height:100%;margin: auto;" v-has="{action: 'coupon:list', effect: 'noPremiss'}">
      <NoPremission></NoPremission>
    </div>
  </div>
</template>
<script>
import request from "@/tools/request";
import Panel from "@/components/Panel";
import TableEncapsulation from "@/components/TableEncapsulation";
import TablePager from "@/components/Pager";
import { objectFilter } from "@/tools/array";
import ModifyForm from "@/components/ModifyForm";
import ModalPanel from "@/components/ModalPanel";
import { dateFormat } from "@/tools/time";
export default {
  name: "couponList1",
  components: {
    TableEncapsulation,
    TablePager,
    Panel,
    ModifyForm,
    ModalPanel,
  },
  data() {
    return {
      intro:{
        title: '',
        content: `直流桩优惠券，可主动发放给单个用户；或者用户主动领取`
      },
      searchs:{
        component: 'coupon',
        name: '',
        grant: '', 
        type: '',
        state:'',
      },
      tableData: [],
      pager: {
        component: 'coupon',
        use: true,
        total: 0,
        current: 1,
        size: 15,
        showTotal: true
      },
      operation: true,
      // 选择优惠券
      pager1: {
        component: 'coupon',
        use: true,
        total: 0,
        current: 1,
        size: 15,
        showTotal: true
      },
      tableDataCoupon:[],
      couponItems: [],
      // end
      //添加编辑
      
      showUpdate: true,
      appointmentTime: null,
      appointmentTimePost: null,
      pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
      visible:false,
      modalData:{},
      siteList: [],
      checkList: [],
      typesList:[],
      typeData:[{'id': '1','name': "自营"},{'id':'2', 'name':"第三方"},{'id':'3', 'name':"租用"},{'id':'9', 'name':"私人"}],
      editColumn: [
        {
          name: "首单电量",
          prop: "elecQuantity",
          type: "number",
          width:24,
          required: true,
          desc:'被邀请人首单电量达到门槛可领取券包'
        },
        {
          name: "有效天数",
          prop: "takeEffectDay",
          type: "number",
          width:24,
          required: true,
        },
        {
          name: "优惠券券包",
          prop: "activityCoupons",
          type: "other",
          width:24,
          required: false,
          slotName: 'CouponList',
        },
      ],
      //添加编辑end
    };
  },
  computed: {
    tableConfig () {
      return {
        selection: true,
        // expand:true,
        columnConfig: [
          {
            label: "编号",
            type: "text",
            prop: "id",
            align: "center",
          },
          {
            label: "首单电量",
            type: "text",
            prop: "elecQuantity",
            align: "center",
          },
          {
            label: "有效天数",
            type: "text",
            prop: "takeEffectDay",
            align: "center"
          },
          
          {
            label: "状态",
            type: "other",
            prop: "state",
            align: "center",
            fnc: val => val == 1 ? "下线" :"上线",
            class:  val => val == 1 ? "cancel" :  "agree" ,
          },
          {
            label: "券包",
            type: "expand",
            prop: "activityCoupons",
            align: "center",
            width:180
          },
          this.operation && {
            type: "operation",
            align: "center",
            label: "操作",
            width:260
          }
        ].filter(Boolean)
        }
    },
    tableConfigCoupon(){
      return {
        selection: false,
        columnConfig: [
          {
            label: "编号",
            type: "text",
            prop: "id",
            align: "center",
          },
          {
            label: "类型",
            type: "other",
            prop: "type",
            align: "center",
            width: '120px',
            fnc: val => val == 1 ? "会员折扣" : val == 2 ? "服务费减免" : "总费用减免",
            class: val => val == 1 ? "red-tag" : val == 2 ? "green-tag" : "sheng1"
          },
          {
            label: "优惠券",
            type: "text",
            prop: "name",
            align: "center",
          },
          this.operation && {
            type: "operation",
            align: "center",
            label: "操作",
          }
        ].filter(Boolean)
        }
    }
  },
  mounted() {
    this.getQueryData();
    this.getCouponList()
  },
  methods: {
    async getQueryData() {
      let current =  this.pager.current
      let size = this.pager.size
      let search = objectFilter({ size, current })
      const res = await request({
        url: `/manage/invite/activity/query`,
        method: "POST",
        data: search
      });
      let data = res.data.records
      data.map(item => {
        if(item.startTimeOfDay){
          item.timedun = item.startTimeOfDay+'至'+item.endTimeOfDay
        }else{
          item.timedun = '全天'
        }
        
        item.priceDesc = `满${item.thresholdAmount}减${item.amount}`
        return item
      })
      this.tableData = data
      this.pager.total = res.data.total
      this.pager.current = res.data.current
    },
    pageChange(val) {
      this.pager.current = val;
      this.getQueryData();
    },
    changeSearch(key, val) {
      this.searchs[key] = val;
      this.pager.current = 1;
    },
    commentDetail(id){
      this.$store.commit('saveSearchs', this.searchs)
      this.$store.commit('savePager', this.pager)
      this.$router.push({ path: "/user/coupon/list",query:{couponId:id,type: "toview"} })
    },
    //添加编辑start
    addCouponItems(row){
      this.couponItems = [...this.couponItems, row]
    },
    deleteCouponItems(index){
      let data = this.couponItems.splice(index, 1)
    },
    async getCouponList(){
      ///manage/coupon/query
      let current =  this.pager1.current
      let size = this.pager1.size
      let search = objectFilter({ size, current })
      const res = await request({
        url: `/manage/coupon/query`,
        method: "POST",
        data: search
      });
      let data = res.data.records
      data.map(iten => {
        iten.name = `满${iten.thresholdAmount}减${iten.amount}`
        return iten
      })
      this.tableDataCoupon = data
    },
    pageChange1(val) {
      this.pager1.current = val;
      this.getQueryData();
    },
    editStore(rowData,state){
      this.visible = true
    },
    async onSubmit(){
      this.$refs['configModal'].onSubmit()
    },
    onCancel(){
      this.showSearch = false
      this.visible = false
      this.checkList =[]
    },
    async updateData(values){
      let {id, takeEffectDay, elecQuantity } = values
      let activityCoupons = this.couponItems
      if(activityCoupons.length<1){
        this.$message.error('请添加活动优惠券包')
        return
      }
      let url = "/manage/invite/activity/add"
      let res = await request({
        url: url,
        method: "POST",
        data:{ id ,elecQuantity, takeEffectDay , activityCoupons}
      })
     if(res.code !==200) return
      this.$message.success('成功')
      this.visible = false
      this.getQueryData();
    },
    //添加编辑end

   //updateState
   async updateState(id, state){
    let res = await request({
        url: '/manage/invite/activity/update/state',
        method: "POST",
        data:{id, state}
      })
     if(res.code !==200) return
      this.$message.success('成功')
      this.getQueryData();
   },
  }
}
</script>
<style lang='scss' >
.coupon-item{
  background: #cd2a2a;
  color: #fff;
  padding: 4px 4px;
  margin-right: 10px;
}
</style>